import java.util.Scanner;

/**
 * @author gao
 * @date 2025/8/26 15:53
 */

public class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int n = nums.length, left = 0, right = n - 1;

        // 找到右边界
        while (left < n - 1 && nums[left] <= nums[left + 1]) {
            left++;
        }

        if (left == n - 1) {
            return 0; // 数组已经有序
        }

        while (right > 0 && nums[right] >= nums[right - 1]) {
            right--;
        }

        // 找到子数组的最小值和最大值
        int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
        for (int i = left; i <= right; i++) {
            min = Math.min(min, nums[i]);
            max = Math.max(max, nums[i]);
        }

        // 扩展左边界
        while (left > 0 && nums[left - 1] > min) {
            left--;
        }

        // 扩展右边界
        while (right < n - 1 && nums[right + 1] < max) {
            right++;
        }

        return right - left + 1;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int n = in.nextInt();
            int[] nums = new int[n];
            for (int i = 0; i < nums.length; i++) {
                nums[i] = in.nextInt();
            }
            Solution solution = new Solution();
            System.out.println(solution.findUnsortedSubarray(nums));
        }
    }
}